<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--左侧搜索-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="dictType"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="add">
          <el-button @click="handleAddLevel1" style="width: 100%"
            >添加一级分类</el-button
          >
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'dictName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expanded-keys="defaultExpandIds"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            :default-expand-all="false"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="edit">
                  <el-tooltip content="添加分类" placement="top">
                    <a @click.stop="append(data)">
                      <el-icon><Plus /></el-icon>
                    </a>
                  </el-tooltip>
                  <el-tooltip content="编辑" placement="top">
                    <a style="margin-left: 8px" @click.stop="handelEdit(data)">
                      <el-icon><Edit /></el-icon>
                    </a>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <a
                      style="margin-left: 8px"
                      @click.stop="handelDelClass(data)"
                    >
                      <el-icon><DeleteFilled /></el-icon>
                    </a>
                  </el-tooltip>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <!--右侧数据-->
      <el-col :span="18" :xs="24">
        <div class="searchForm">
          <!-- <el-button @click="resetSearch" icon="RefreshRight">重置</el-button> -->

          <el-form
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="产品名称" prop="bookName">
              <el-input
                placeholder="请输入产品名称"
                v-model="searchQuery.model.productName"
              />
            </el-form-item>
            <el-form-item label="状态" prop="bookName">
              <el-select
                v-model="searchQuery.model.productState"
                placeholder="请选择"
              >
                <el-option label="审批中" :value="1"></el-option>
                <el-option label="已上传" :value="2"></el-option>
                <el-option label="草稿" :value="0"></el-option>
                <el-option label="审批拒绝" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="来源" prop="bookName">
              <el-select
                v-model="searchQuery.model.resourceType"
                placeholder="请选择"
              >
                <el-option label="前台" :value="0"></el-option>
                <el-option label="后台" :value="1"></el-option>
                <el-option label="批量上传" :value="2"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="getModelList" icon="Search"
                >搜索</el-button
              >
              <el-button @click="resetSearch" icon="RefreshRight"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="search">
          <el-button @click="uploadmodel" icon="Upload" type="primary"
            >上传模型</el-button
          >
          <el-dropdown>
            <el-button type="primary" style="margin: 0 10px">
              上传文件<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="gropUploadmodel(false)"
                  >选择文件</el-dropdown-item
                >
                <el-dropdown-item @click="gropUploadmodel(true)"
                  >选择文件夹</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- <el-button
            @click="gropUploadmodel(true)"
            :disabled="!isBatchUpload"
            type="primary"
            icon="Upload"
            style="margin-right: 10px"
            >文件夹上传模型</el-button
          >

          <el-button
            @click="gropUploadmodel(false)"
            :disabled="!isBatchUpload"
            type="primary"
            icon="Upload"
            style="margin-right: 10px"
            >批量上传模型</el-button
          > -->
          <input
            v-show="false"
            ref="fileInput"
            type="file"
            :webkitdirectory="isFolder"
            directory
            multiple
            @change="handleFileSelect"
          />

          <el-button
            :disabled="!tableSelected.length > 0"
            @click="addDomain(42)"
            >添加到领域</el-button
          >
          <el-button
            :disabled="!tableSelected.length > 0"
            @click="addDomain(43)"
            >添加到专题</el-button
          >
          <el-button type="primary" icon="Edit" @click="openSortRuleDialog"
            >设置排序规则</el-button
          >
        </div>
        <div class="searchInput"></div>
        <el-table
          ref="tableRef"
          :data="modelList"
          @select="handleSelectionChange"
          @select-all="handleSelectionChange"
          @row-click="handelRowClick"
        >
          <el-table-column type="selection" width="80" align="center" />
          <el-table-column
            label="来源"
            align="center"
            width="80"
            prop="productCode"
          >
            <template #default="scope">
              <span class="el-tag">{{
                backgroundDictMap(scope.row.resourceType)
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="缩略图" align="center">
            <template #default="scope">
              <el-image
                style="width: 50px; height: 50px"
                preview-teleported
                :src="
                  scope.row.fileList.length > 0
                    ? scope.row.fileList[0].filePath
                    : ''
                "
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="
                  scope.row.fileList.length > 0
                    ? scope.row.fileList.map((item) => item.filePath)
                    : []
                "
                :initial-index="4"
                fit="cover"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="产品名称"
            align="center"
            prop="productName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="分类"
            prop="dictName"
            align="center"
            key="status"
            width="240"
          >
            <template #default="scope">
              <!-- <span>{{ getOneName(scope.row.dictName) }}</span> -->
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            prop="productState"
            width="80"
          >
            <template #default="scope">
              <div
                class="el-tag el-tag--success"
                v-if="scope.row.productState == 2"
              >
                已上传
              </div>
              <div class="el-tag" v-if="scope.row.productState == 1">
                审批中
              </div>
              <div
                class="el-tag el-tag--warning"
                v-if="scope.row.productState == 0"
              >
                草稿
              </div>
              <div
                class="el-tag el-tag--danger"
                v-if="scope.row.productState == 3"
              >
                审批拒绝
              </div>
            </template>
          </el-table-column>
          <!-- 备注 -->

          <el-table-column label="备注" align="center" prop="productState">
            <template #default="scope">
              <div
                v-if="
                  scope.row.resourceType == 2 && scope.row.fileList.length == 0
                "
              >
                批量上传，未上传缩略图
              </div>
              <div v-else></div>
            </template>
          </el-table-column>
          <!-- 备注 -->
          <el-table-column align="center" label="上架状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.shelfStatus"
                :active-value="1"
                :inactive-value="0"
                @click="changeShow(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="上传时间"
            align="center"
            prop="createtime"
            width="160"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
              <!-- <span>{{ scope.row.createTime }}</span> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="searchQuery.current"
          v-model:limit="searchQuery.size"
          @pagination="getModelList"
          small
        />
      </el-col>

      <!-- 添加分类log框 -->
      <el-dialog
        :title="`${classForm.id ? '编辑' : '新增'}分类`"
        v-model="classdialogVisible"
        width="30%"
        @close="beforeClose1"
      >
        <el-form
          :model="classForm"
          ref="ruleFormRef"
          label-width="120px"
          :rules="rules1"
        >
          <el-form-item label="分类" prop="dictName">
            <el-input v-model="classForm.dictName" style="width: 300px" />
          </el-form-item>
          <el-form-item label="编码" prop="dictValue">
            <el-input
              v-model="classForm.dictValue"
              :disabled="isEdit"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="排序" prop="dictSequence">
            <el-input
              v-model.number="classForm.dictSequence"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="表代码" prop="dictCode">
            <el-select
              v-model="classForm.dictCode"
              class="m-2"
              placeholder="请选择表代码"
              style="width: 300px"
            >
              <el-option
                v-for="item in dictCodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="classdialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handelNewClass"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 右侧展示信息的抽屉 -->
      <el-drawer v-model="drawer" size="50%" title="基本信息">
        <template #default>
          <div class="info">
            <div class="name">产品名称：{{ infoForm.productName }}</div>
            <el-row>
              <el-col :span="12">
                <span class="ltitle">上传者:</span>
                <span> {{ infoForm.createBy }}</span>
              </el-col>
              <el-col :span="12">
                <span class="ltitle">上传时间:</span>
                <span> {{ parseTime(infoForm.createTime) }}</span>
              </el-col>
            </el-row>

            <el-row>
              <span class="ltitle">模型分类:</span>
              <span> {{ infoForm.dictName }}</span>
            </el-row>
            <el-row>
              <span class="ltitle">来源:</span>
              <span> {{ backgroundDictMap(infoForm.resourceType) }}</span>
            </el-row>
            <el-row>
              <el-col :span="24">
                <span class="ltitle">产品描述:</span>
                <span>{{ infoForm.productNotes }}</span>
              </el-col>
            </el-row>
            <el-row>
              <span class="ltitle">开放权限:</span>
              <span> 开放下载</span>
            </el-row>

            <el-tabs
              v-model="infoTabActive"
              class="demo-tabs"
              @tab-click="handleChangeInfoClick"
            >
              <el-tab-pane label="模型参数" name="first">
                模型参数
              </el-tab-pane>
              <el-tab-pane label="模型展示" name="second">模型展示</el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <template #footer>
          <div style="flex: auto">
            <div style="display: flex; justify-content: space-between">
              <el-button type="danger" @click="handelDelModel">删除</el-button>
              <div>
                <el-button type="primary" @click="handelInfoEdit(0)"
                  >编辑</el-button
                >
                <el-button type="primary" @click="handelInfoEdit(1)"
                  >查看</el-button
                >
                <el-button @click="drawer = false">取消</el-button>
              </div>
            </div>
          </div>
        </template>
      </el-drawer>

      <!-- 添加领域/专题对话框 -->
      <el-dialog
        :title="domainTitle"
        v-model="domainDialog"
        width="30%"
        @close="beforeClose2"
      >
        <el-cascader
          style="width: 100%"
          v-model="domainIds"
          :options="domainList"
          :props="{
            multiple: true,
            emitPath: false,
            label: 'areaTitle',
            value: 'id',
            children: 'children',
          }"
          clearable
        />
        <template #footer>
          <el-button @click="domainDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitDomain">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 添加排序规则弹窗 -->
      <el-dialog
        title="设置排序规则"
        v-model="sortRuleDialog"
        width="40%"
        @close="beforeClose3"
      >
        <el-form
          ref="sortRuleFormRef"
          :model="sortRuleForm"
          label-width="140px"
        >
          <el-form-item label="浏览量(百分比)：">
            <el-slider
              v-model="sortRuleForm.viewRate"
              show-input
              :marks="marks"
            />
          </el-form-item>
          <el-form-item label="下载量(百分比)：">
            <el-slider
              v-model="sortRuleForm.downloadRate"
              show-input
              :marks="marks"
            />
          </el-form-item>
          <el-form-item label="收藏量(百分比)：">
            <el-slider
              v-model="sortRuleForm.collectionRate"
              show-input
              :marks="marks"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="sortRuleDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitSortRules">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 显示上传进度的对话框 -->
      <transition name="fade">
        <div class="upload" v-if="uploadflag">
          <div class="header">
            <div>
              正在上传({{ uploadlist.filter((item) => item.id).length }}/{{
                uploadlist.length
              }})
            </div>
            <div
              class="close"
              @click="
                () => {
                  uploadflag = false;
                  uploadlist = [];
                }
              "
            >
              <el-icon><CloseBold /></el-icon>
            </div>
          </div>
          <div class="edit">
            <div>
              <el-input
                placeholder="请输入模型名称"
                v-model="searchUploadList"
                style="width: 200px; padding: 8px 4px"
                @input="searchUploadListChange"
              >
                <el-icon slot="suffix" style="color: yellow"
                  ><WarningFilled
                /></el-icon>
              </el-input>
            </div>
            <div class="clear">
              <div
                style="cursor: pointer; margin-right: 10px"
                @click="clearUploaded"
              >
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="清除已上传"
                  placement="top"
                >
                  <el-icon><Delete /></el-icon>
                </el-tooltip>
              </div>
              <div style="cursor: pointer" @click="clearAll">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="清除全部"
                  placement="top"
                >
                  <el-icon><DeleteFilled /></el-icon>
                </el-tooltip>
              </div>
            </div>
          </div>
          <div class="uplist">
            <div class="item" v-for="(item, index) in uploadlist">
              <!-- <div>{{ }}</div> -->
              <div style="width: 200px" class="ellipsis">
                {{ item.name }}
              </div>

              <div>{{ (item.size / 1024 / 1000).toFixed(2) }}M</div>
              <div class="status" v-if="item.id == ''">
                <el-icon style="color: yellow"><WarningFilled /></el-icon>上传中
              </div>
              <div class="status" v-else-if="item.id == '-1'">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.msg"
                  placement="top"
                >
                  <div>
                    <el-icon style="color: red"><CircleCloseFilled /></el-icon>
                    上传失败
                  </div>
                </el-tooltip>
              </div>
              <div class="status" v-else>
                <el-icon style="color: green"><CircleCheckFilled /></el-icon>
                上传成功
              </div>
              <div style="cursor: pointer" @click="deleteFile(item, index)">
                <el-icon><DeleteFilled /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </el-row>
  </div>
</template>

<script setup>
import {
  queryModelDictPage,
  insertModelType,
  updateModelType,
  deleteModelType,
  importModelDict,
  downModelDict,
  queryModelFirst,
  queryModelByParentId,
  updateModelTypeBatch,
  queryModelPage,
  deleteModel,
  getDickAllTreeListRequest,
  checkUploadStatusRequest,
  getDeteilImgByIdRequest,
  getModelTypeListRequest,
  addModelToDomainOrTopic,
  saveModelRequest,
  editModelRequest,
  uploadGrupFileRequest,
} from "@/api/buildlibrary";
import {
  getDomainListRequest,
  getSortRuleRequest,
  setSortRuleRequest,
} from "@/api/buildlibrary/domain.js";
import { useRouter, useRoute } from "vue-router";

import { ref, reactive, onMounted, watch, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import useBuildlibraryStore from "@/store/modules/buildlibrary";
import Operate from "../modelmanagement/operate.vue";
const { proxy } = getCurrentInstance();
const router = useRouter();

const route = useRoute();

//初始化
const uploadflag = ref(false);
const uploadstatus = ref(0);
const modelname = ref("");
const tableRef = ref(null);
function init() {
  // const {
  //   params: { message, modelName },
  // } = route;
  const message = useBuildlibraryStore().message;
  const modelName = useBuildlibraryStore().modelName;
  modelname.value = modelName;
  if (message) {
    uploadflag.value = true;
    console.log(message, modelName);
    //轮询检查上传状态
    const timer = setInterval(async () => {
      const res = await checkUploadStatusRequest({ key: message });
      console.log(res);
      if (res.message !== "0") {
        //上传出结果了 1成功 2失败
        uploadstatus.value = res.message;

        clearInterval(timer);
      }
    }, 2000);
  }
}
//离开页面操作
onUnmounted(() => {
  const message = useBuildlibraryStore().message;
  if (message) useBuildlibraryStore().message = "";
});

onMounted(() => {
  init();
  // 树形菜单获取
  getTreeList();
  // 获取数据
  getModelList();
  //获取字典数据
  getDictCodeOptions();
});

//表代码接口获取
const dictCodeOptions = ref([]);
//前后台字典
const backgroundDict = ref([]);
const getDictCodeOptions = async () => {
  const res = await getModelTypeListRequest({ size: 999, model: { type: 9 } });
  const res1 = await getModelTypeListRequest({
    size: 999,
    model: { type: 11 },
  });
  dictCodeOptions.value = res.data.records;

  backgroundDict.value = res1.data.records;
  console.log(res.data.records);
};

//列表映射方法 backgroundDict
function backgroundDictMap(id) {
  return backgroundDict.value.find((item) => item.value == id)?.label;
}

const dictType = ref("");
const deptOptions = ref([]);

const defaultExpandIds = ref([]); // 这里存放要默认展开的节点 id\
// 树节点展开
const handleNodeExpand = (data) => {
  // 保存当前展开的节点
  let flag = false;
  defaultExpandIds.value.some((item) => {
    if (item === data.id) {
      // 判断当前节点是否存在， 存在不做处理
      flag = true;
      return true;
    }
  });
  if (!flag) {
    // 不存在则存到数组里
    defaultExpandIds.value.push(data.id);
  }
};
// 树节点关闭
const handleNodeCollapse = (data) => {
  // 删除当前关闭的节点
  defaultExpandIds.value.some((item, i) => {
    if (item === data.id) {
      defaultExpandIds.value.splice(i, 1);
    }
  });
  removeChildrenIds(data); // 这里主要针对多级树状结构，当关闭父节点时，递归删除父节点下的所有子节点
};
// 删除树子节点
const removeChildrenIds = (data) => {
  if (data.children) {
    data.children.forEach(function (item) {
      const index = defaultExpandIds.value.indexOf(item.id);
      if (index > 0) {
        defaultExpandIds.value.splice(index, 1);
      }
      removeChildrenIds(item);
    });
  }
};
//重置搜索
const resetSearch = () => {
  // deptTreeRef.value
  var nodes = proxy.$refs["deptTreeRef"].store.nodesMap;
  for (var i in nodes) {
    nodes[i].expanded = false;
  }

  searchQuery.current = 1;
  searchQuery.size = 10;
  searchQuery.model.classifyId = "";
  searchQuery.model.productName = "";
  searchQuery.model.productState = "";
  searchQuery.model.resourceType = "";

  isBatchUpload.value = false;
  getModelList();
};

/** 根据名称筛选部门树 */
watch(dictType, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.dictName.indexOf(value) !== -1;
};

//获取左侧树形列表
const getTreeList = async () => {
  const res = await getDickAllTreeListRequest({ level: 5, dictType: 1 });
  deptOptions.value = res.data;
  console.log(res);
};

const Allids = ref([]);
/** 节点单击事件 */
function handleNodeClick(nodeData) {
  // 递归查找所有父节点
  const parentNodes = findParentNodes(nodeData);
  parentNodes.unshift(nodeData.id);
  let ids = parentNodes.reverse();
  console.log(ids);
  console.log(nodeData);
  let topName = findParentNodesDictName(ids[0]);
  Allids.value = ids;
  //请求数据
  searchQuery.model.classifyId = nodeData.id;
  //设置可以批量上传
  isBatchUpload.value = true;
  currentDictValue.value = nodeData.dictValue;
  currentDictName.value = topName;
  getModelList();
}

function findParentNodes(nodeData) {
  const parentNodes = [];
  let treeref = proxy.$refs["deptTreeRef"];
  // console.log(nodeData);
  const findParent = (node) => {
    let pid = treeref.getNode(node).parent.data.id || 0;
    // console.log(treeref.getNode(node).parent.data);
    if (pid !== 0) {
      parentNodes.push(pid);
      findParent(treeref.getNode(node).parent.data);
    }
  };
  findParent(nodeData);
  return parentNodes;
}
function findParentNodesDictName(id) {
  //递归 deptOptions.value 找到和传进来的id相同的 返回出去
  let name = "";
  deptOptions.value.forEach((item) => {
    console.log(item.id);
    if (item.id === id) {
      name = item.dictName;
    }
  });

  return name;
}
//删除模型分类事件
const handelDelClass = (row) => {
  console.log(row);
  let id = row.id;
  // return;
  ElMessageBox.confirm("你确定要删除此分类吗?", "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const { code } = await deleteModelType({ ids: [id] });
        if (code === 200) {
          ElMessage.success(`删除成功`);
          getTreeList();
        } else {
          ElMessage.error(`服务器故障，稍后再试`);
        }
      } catch (error) {}
    })
    .catch(() => {});
};

//添加分类的表单
let classForm = reactive({
  dictName: "", //分类名称
  dictValue: "", //编码
  dictType: "1", //dictType
  parentId: 0, //父ID
  dictStatus: 0, //状态
  dictSequence: 0, //排序
  dictCode: "14", //表代码
});
//分类规则
const rules1 = reactive({
  dictName: [{ required: true, message: "请输入分类", trigger: "blur" }],
  dictValue: [{ required: true, message: "请输入编码", trigger: "blur" }],
  dictCode: [{ required: true, message: "请选择表代码", trigger: "blur" }],
});
//添加分类的显示隐藏
const classdialogVisible = ref(false);
const ruleFormRef = ref(null);

const parentDictValue = ref(null);
//新建分类方法
const append = (row) => {
  classdialogVisible.value = true;
  console.log(row);
  classForm.dictValue = row.dictValue + (row.children.length + 1);
  classForm.dictSequence = row.children.length + 1;
  parentDictValue.value = row.dictValue;
  classForm.dictType = "1";
  classForm.parentId = row.id;
};
//新建顶级分类
const handleAddLevel1 = () => {
  classdialogVisible.value = true;
  classForm.parentId = 0;
  parentDictValue.value = null;
};

let isEdit = ref(false); //是否编辑
//编辑分类表单事件
const handelEdit = (row) => {
  console.log(row);
  isEdit.value = true;
  classdialogVisible.value = true;
  classForm.dictName = row.dictName; //分类名称
  classForm.dictValue = row.dictValue; //编码
  classForm.parentId = row.parentId; //父级名称
  classForm.dictType = "1"; //类型
  classForm.dictStatus = 0; //状态
  classForm.id = row.id; //id
  classForm.dictSequence = row.dictSequence; //排序
  classForm.dictCode = row.dictCode; //表代码
};

//新建分类提交表单确认方法
const handelNewClass = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        ...classForm,
      };

      data.dictValue =
        (parentDictValue.value ? parentDictValue.value : "") + data.dictValue;
      console.log(data);
      // return;
      let fun = data.id ? updateModelType : insertModelType;
      const { code } = await fun(data);
      if (code === 200) {
        ElMessage.success(`${data.id ? "编辑" : "添加"}成功`);
        classdialogVisible.value = false;
        parentDictValue.value = null;
        getTreeList();
      } else {
        ElMessage.error("服务故障，稍后再试");
        parentDictValue.value = null;
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//关闭dlog回调
const beforeClose1 = () => {
  isEdit.value = false; //退出编辑模式
  ruleFormRef.value.resetFields();
  console.log(1123123);
  //数据初始化
  classForm = reactive({
    dictName: "",
    dictValue: "",
    dictType: "1",
    parentId: 0,
    dictStatus: 0,
    dictSequence: 0,
    dictCode: "14",
  });
};

//表格数据表单
const searchQuery = reactive({
  model: {
    // treeCode: "",
    classifyId: "",
  },
  current: 1,
  size: 10,
});
let total = ref(0);
const modelList = ref([]);
const getModelList = async () => {
  const res = await queryModelPage(searchQuery);

  modelList.value = res.data.records;
  total.value = res.data.total;

  // 遍历数据，获取图片地址
  for (let i = 0; i < modelList.value.length; i++) {
    let imgs = modelList.value[i].shrinkageChartFileIds?.split(",") || [];
    if (imgs[0]) {
      modelList.value[i].imageUrl = await getImageUrl(imgs[0]);
    }
  }
  // modelList.value.forEach(async (item) => {
  //   item.imageUrl = await getImageUrl(item.shrinkageChartFileIds);
  // });
};

let tableSelected = ref([]);
//表格选择事件
const handleSelectionChange = (val, row) => {
  // console.log(val, row.id);
  tableSelected.value = val.map((item) => {
    return item.id;
  });
};

//抽屉开关
const drawer = ref(false);
//抽屉信息tabs
let infoTabActive = ref("first");
//抽屉信息切换事件
const handleChangeInfoClick = (tab, event) => {
  console.log(infoTabActive.value);
};

//上传模型
const uploadmodel = () => {
  console.log(Allids.value);
  router.push({
    path: "/buildlibrary/componentLibUpload",
  });
};

//是否可以批量上传模型标识
let isBatchUpload = ref(false);
let fileInput = ref(null);
//当前选择的currentDictValue
let currentDictValue = ref("");
//当前选择的  dictName
let currentDictName = ref("");
//批量上传模型按钮

//是否文件夹上传
const isFolder = ref(false);
const gropUploadmodel = async (flag) => {
  //判断一下 有没有点击左侧菜单，如果没有 提示先选择
  if (!isBatchUpload.value) {
    ElMessage.error("请先选择左侧菜单");
    return;
  }
  isFolder.value = flag;
  // fileInput.value.==.click();
  fileInput.value.click();
};
let uploadlist = ref([]);
const handleFileSelect = async (event) => {
  //断点

  // 清空uploadlist 上传列表
  uploadlist.value = [];
  const files = event.target.files;
  console.log(files);
  let strList = [
    "adsk",
    "pcg",
    "rfa",
    "rvt",
    "slog",
    "rft",
    "pmk",
    "pla",
    "prf",
    "mod",
    "tpl",
    "aat",
    "spr",
    "rpr",
    "lbk",
    "lcy",
    "2dl",
    "lay",
    "pln",
    "pce",
    "pc",
    "pcx",
    "pbims2",
    "fbx",
    "csd",
    "p3d",
  ];
  let reqList = [];
  for (let i = 0; i < files.length; i++) {
    let str = files[i].name;
    let index = str.lastIndexOf("\.");
    let newstr = str.substring(index + 1, str.length);
    if (strList.includes(newstr)) {
      console.log(files[i]);
      let formData = new FormData();
      formData.append("dictValue", currentDictValue.value);
      formData.append("dictName", currentDictName.value);
      formData.append("file", files[i]);
      formData.append("fileName", files[i].name);
      formData.append("fileSize", files[i].size);

      reqList.push(uploadGrupFileRequest(formData));

      uploadflag.value = true;
      uploadlist.value.push({
        name: files[i].name,
        size: files[i].size,
        id: "",
        msg: "",
      });
    }
  }
  // console.log(reqList);

  reqList.forEach(async (item, index) => {
    try {
      let res = await item;
      if (res.code == 200) {
        uploadlist.value[index].id = res.msg;
        localStorage.setItem("uploadlist", JSON.stringify(uploadlist.value));
      } else {
      }

      if (index >= reqList.length - 1) {
        getModelList();
      }
    } catch (error) {
      uploadlist.value[index].id = "-1";
      uploadlist.value[index].msg = error;
      console.log(error);
    }
  });

  // getModelList();
  // console.log(res);

  // traverseFiles(files, formData);
  // console.log(formData);
};
// function traverseFiles(files, formData) {
//   for (let i = 0, len = files.length; i < len; i++) {
//     const file = files[i];
//     console.log(file);
//     if (file.isDirectory()) {
//       traverseFiles(file, formData);
//     } else {
//       const name = file.webkitRelativePath || file.name;
//       formData.append("files[]", file, name);
//     }
//   }
// }

const infoForm = ref({});
//表格每行单机事件
const handelRowClick = (row, column) => {
  // console.log(row, column);
  if (column.property !== undefined) {
    drawer.value = true;
    infoForm.value = row;
  }
};

//模型删除事件
const handelDelModel = () => {
  console.log(infoForm.value.id);
  ElMessageBox.confirm("确定要删除此模型吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteModel(infoForm.value.id);
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getModelList();
        drawer.value = false;
      }
    })
    .catch(() => {});
};

//抽屉 编辑事件
const handelInfoEdit = (flag) => {
  console.log(flag);
  if (flag == 1) {
    router.push({
      path: "/buildlibrary/componentLibUpload",
      query: { id: infoForm.value.id, view: 1 },
    });
  } else {
    console.log(infoForm.value);
    router.push({
      path: "/buildlibrary/componentLibUpload",
      query: { id: infoForm.value.id },
    });
  }
};

//获取图片地址
const getImageUrl = async (id) => {
  const res = await getDeteilImgByIdRequest(id);
  let blob = new Blob([res]);
  let url = window.URL.createObjectURL(blob);
  // console.log(url);

  return url;
};

//添加领域/专题的dialog框
const domainDialog = ref(false);
const domainList = ref([]);
const domainIds = ref([]);
let domainTitle = ref("");
const addDomain = async (type) => {
  if (type === 42) {
    domainTitle.value = "添加到领域";
  } else {
    domainTitle.value = "添加到专题";
  }
  domainDialog.value = true;
  const res = await getDomainListRequest({
    current: 1,
    size: 999,
    model: {
      type: type,
      shelfStatus: 1,
    },
  });
  if (type === 42) {
    res.data.records.forEach((item) => {
      if (!item.children.length > 0) {
        item.disabled = true;
      }
    });
  }
  domainList.value = res.data.records;
  console.log(res);
};

const beforeClose2 = () => {
  domainIds.value = [];
};

// 提交 领域
const submitDomain = async () => {
  if (domainIds.value.length < 1) {
    return ElMessage.error(`请选择分类`);
  }
  const res = await addModelToDomainOrTopic({
    // 调用 addModelToDomainOrTopic 方法，传入 modelIds 和 businessIds 参数
    modelIds: tableSelected.value, // 将 tableSelected 的值赋值给 modelIds
    businessIds: domainIds.value, // 将 domainIds 的值赋值给 businessIds
  });
  if (res.data) {
    // 如果 res 的 data 属性存在
    ElMessage.success("添加成功！"); // 显示成功提示信息
    setTimeout(() => {
      domainDialog.value = false; // 关闭 domainDialog
      tableRef.value.clearSelection(); // 清除表格选择
      tableSelected.value = []; // 将 tableSelected 置为空数组
    }, 500);
  }
};

//状态改变事件
async function changeShow(row) {
  const { shelfStatus, id } = row;

  let data = {
    id,
    shelfStatus,
  };
  const res = await editModelRequest(data);
  console.log(res);
  if (res.code === 200) {
    ElMessage.success("状态修改成功！");
    getModelList();
  }
}

//打开排序规则
const openSortRuleDialog = async () => {
  sortRuleDialog.value = true;

  const res = await getSortRuleRequest({ model: { type: 0 } });
  let data = res.data.records[0];
  sortRuleForm.viewRate = data.viewRate * 100;
  sortRuleForm.downloadRate = data.downloadRate * 100;
  sortRuleForm.collectionRate = data.collectionRate * 100;
  console.log(res);
};
//关闭排序规则
const beforeClose3 = () => {
  sortRuleForm.viewRate = 0;
  sortRuleForm.downloadRate = 0;
  sortRuleForm.collectionRate = 0;
};
//排序规则的dialog
let sortRuleDialog = ref(false);
//排序提示
const marks = reactive({
  0: "0%",
  25: "25%",
  50: "50%",
  75: "75%",
  100: "100%",
});
//排序规则表单
let sortRuleForm = reactive({
  viewRate: 0,
  downloadRate: 0,
  collectionRate: 0,
});
//排序规则提交表单
const submitSortRules = async () => {
  const res = await setSortRuleRequest({
    id: 1,
    viewRate: sortRuleForm.viewRate / 100,
    downloadRate: sortRuleForm.downloadRate / 100,
    collectionRate: sortRuleForm.collectionRate / 100,
  });
  console.log(res);
  if (res.data) {
    ElMessage.success("排序规则修改成功！");
    sortRuleDialog.value = false;
  }
};
//上传列表删除
const deleteFile = (item, index) => {
  uploadlist.value.splice(index, 1);
};

//上传列表清空
const clearAll = () => {
  uploadlist.value = [];
};
//清空已上传
const clearUploaded = () => {
  uploadlist.value = uploadlist.value.filter((item) => {
    return item.id == "-1" || item.id == "";
  });
};
let searchUploadList = ref("");
const searchUploadListChange = (value) => {
  console.log(value);
  //搜索uploadList
  let mapArray = JSON.parse(localStorage.getItem("uploadlist"));
  // 判断输入框是否有值
  if (value) {
    //这个值为输入框输入的值
    var brr = mapArray.filter((item) => {
      //遍历数组，返回值为true保留并复制到新数组，false则过滤掉
      return item.name.includes(value.trim());
    });
    uploadlist.value = brr;
  } else {
    // 如果输入框没值,直接赋值本地存储的数据
    uploadlist.value = mapArray;
  }
};
</script>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .edit {
    display: none;
  }
  &:hover {
    // display: block;
    // background-color: red;
    .edit {
      display: block;
    }
  }
}
.info {
  .name {
    font-weight: bold;
    font-size: 22px;
  }
  .ltitle {
    color: #666;
    width: 80px;
  }
  .el-row {
    margin-top: 10px;
    .el-col {
      display: flex;
    }
  }
}

.upload {
  position: fixed;
  z-index: 3;
  right: 0;
  bottom: 0;
  background-color: #fff;
  width: 600px;
  height: 400px;
  box-shadow: 1px 2px 3px 4px #ccc;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    font-size: 14px;
    height: 40px;
    border-bottom: 1px solid #ccc;
    .close {
      cursor: pointer;
    }
  }
  .edit {
    padding: 0 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .clear {
      display: flex;
    }
  }
  .uplist {
    transition: 0.3s;
    height: 300px;
    overflow-y: auto;
    .item {
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 12px;
      font-size: 12px;
      border-bottom: 1px solid #ccc;
      .status {
        display: flex;
        align-items: center;
        .el-icon {
          margin-right: 6px;
        }
      }
    }
  }
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
